package com.xia.util.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 切面类
 */
@Slf4j
@Aspect
@Component
public class PageViewAspect {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    //通过注解进入切入点
    @Pointcut("@annotation(com.xia.util.annotation.GainPageView)")
    public void PageViewPointcut() {}

    @Before("PageViewPointcut()")
    public void around(JoinPoint joinPoint){
        Object[] obj= joinPoint.getArgs();
        if (obj[2].equals("undefined")){
            log.info("没有用户登录");
        }else {
            //获取切入点中的类参数数据
            Object articleId=obj[0];
            String ip=(String)obj[1];
            //创建被访问的文章ID key
            String key="article_"+articleId;
            //将访问的IP放入被访问的文章ID中
            Long num=redisTemplate.opsForSet().add(key,ip);
            //判断访问IP放入set后是否重复
            if (num != 0){
                //创建被访问的问的浏览量
                String pageViewKey="pageView_"+articleId;
                //redis中浏览量自增
                redisTemplate.opsForValue().increment(pageViewKey);
                return;
            }
            log.info("已重复浏览了哦");
        }
    }
}
